import os
import shutil


class SpecifyFileCleaner:
    def __init__(self, directory):
        self.directory = directory

    def clean_by_name(self, filename):
        """
        递归删除指定名称的文件或文件夹
        """
        for root, dirs, files in os.walk(self.directory, topdown=False):
            for name in files + dirs:
                if name == filename:
                    path = os.path.join(root, name)
                    self._delete(path)

    def clean_by_prefix(self, prefix):
        """
        递归删除指定前缀的文件或文件夹
        """
        for root, dirs, files in os.walk(self.directory, topdown=False):
            for name in files + dirs:
                if name.startswith(prefix):
                    path = os.path.join(root, name)
                    self._delete(path)

    def clean_hidden(self):
        """
        递归删除以.开头的隐藏文件或文件夹
        """
        for root, dirs, files in os.walk(self.directory, topdown=False):
            for name in files + dirs:
                if name.startswith('.'):
                    path = os.path.join(root, name)
                    self._delete(path)

    def clean_empty_dirs(self):
        """
        递归删除空文件夹
        """
        for root, dirs, files in os.walk(self.directory, topdown=False):
            for dir_name in dirs:
                path = os.path.join(root, dir_name)
                if not os.listdir(path):
                    self._delete(path)

    def _delete(self, path):
        """
        删除文件或文件夹
        """
        try:
            if os.path.isfile(path) or os.path.islink(path):
                os.remove(path)
                print(f"Deleted file: {path}")
            elif os.path.isdir(path):
                shutil.rmtree(path)
                print(f"Deleted directory: {path}")
        except Exception as e:
            print(f"Failed to delete {path}. Reason: {e}")


# 使用示例
if __name__ == "__main__":
    cleaner = SpecifyFileCleaner('/Volumes/home/A1-我的文档/')
    cleaner.clean_by_name('.DS_Store')
    cleaner.clean_by_prefix('~')
    cleaner.clean_hidden()
    cleaner.clean_empty_dirs()
